<template>
  <el-dialog
    :visible.sync="dialogVisible"
    top="10vh"
    append-to-body
    :close-on-click-modal="false"
    class="tag-edit-dialog tag-rules-edit-dialog"
    width="50%"
    @closed="clearDialog"
    v-dialogMove
  >
    <div slot="title">
      <tag-content-header>
        <template #title>
          <span class="title-text">{{ dialogTitle[dialogType] }}</span>
        </template>
      </tag-content-header>
    </div>
    <el-form :model="ruleForm" label-width="0px" :rules="ruleFormRules" ref="ruleForm" class="rule-form">
      <el-row>
        <el-col :span="12">
          <el-form-item label="规则名称" prop="ruleNm" label-width="80px">
            <el-input placeholder="请输入规则名称" v-model="ruleForm.ruleNm"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="rule-box">
        <el-row :gutter="20" v-if="ruleForm.ruleList.length !== 0" class="rule-title">
          <el-col :span="5" :offset="3">类型</el-col>
          <el-col :span="5">运算符</el-col>
          <el-col :span="8">规则值</el-col>
        </el-row>
        <el-row :gutter="20" v-for="(item, index) in ruleForm.ruleList" :key="index">
          <el-col :span="3" class="button-col-right">
            <el-button type="primary" @click="shiftItem('up', index)" plain circle v-show="index !== 0">
              <icon-svg name="iconArrowUp"></icon-svg>
            </el-button>
            <el-button
              type="primary"
              @click="shiftItem('down', index)"
              plain
              circle
              v-show="index !== ruleForm.ruleList.length - 1"
            >
              <icon-svg name="iconArrowDown"></icon-svg>
            </el-button>
          </el-col>
          <el-col :span="5">
            <el-form-item
              :prop="'ruleList.' + index + '.ruleVar'"
              :rules="{
                required: true,
                message: '类型不能为空',
                trigger: 'change'
              }"
            >
              <el-select v-model="item.ruleVar" placeholder="请选择类型">
                <template v-for="dict in $dictList('user_rule_type')">
                  <el-option :key="dict.key" :label="dict.value" :value="dict.key"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              :prop="'ruleList.' + index + '.conditionRela'"
              :rules="{
                required: true,
                message: '运算符不能为空',
                trigger: 'change'
              }"
            >
              <el-select v-model="item.conditionRela" placeholder="请选择运算符">
                <el-option label="等于" :value="1"></el-option>
                <el-option label="不等于" :value="2"></el-option>
                <el-option label="包含" :value="3"></el-option>
                <el-option label="不包含" :value="4"></el-option>
                <el-option label="开头是" :value="5"></el-option>
                <el-option label="开头不是" :value="6"></el-option>
                <el-option label="结尾是" :value="7"></el-option>
                <el-option label="结尾不是" :value="8"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :prop="'ruleList.' + index + '.ruleVal'"
              :rules="[
                {
                  required: true,
                  message: '值不能为空',
                  trigger: ['blur', 'change']
                },
                { max: 100, message: '规则值不能超过100个字符', trigger: ['blur', 'change'] }
              ]"
            >
              <el-input placeholder="请输入规则值" v-model="item.ruleVal"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" class="button-col-left">
            <el-button type="primary" icon="el-icon-plus" plain circle @click="addRule(index + 1)"></el-button>
            <el-button
              type="primary"
              icon="el-icon-minus"
              plain
              circle
              @click="removeRule(index)"
              v-if="ruleForm.ruleList.length > 1"
            ></el-button>
          </el-col>
          <el-col :span="5" :offset="3" v-if="index !== ruleForm.nexusList.length" class="nexus-col">
            <el-radio-group v-model="ruleForm.nexusList[index].nexus">
              <el-radio :label="1">与</el-radio>
              <el-radio :label="2">或</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      dialogType: 'add',
      dialogTitle: {
        add: '新增规则模板',
        edit: '修改规则模板'
      },
      ruleForm: {
        id: '',
        ruleNm: '',
        ruleList: [],
        nexusList: []
      },
      ruleFormRules: {
        ruleNm: [
          { required: true, message: '规则名称不能为空', trigger: 'blur' },
          { max: 30, message: '规则名称不能超过30个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    showDialog(params) {
      this.dialogType = params.type
      if (params.type === 'edit') {
        this.ruleForm.id = params.id
        this.ruleForm.ruleNm = params.name
        this.setList(params.list)
      }
      if (this.ruleForm.ruleList.length === 0) this.addRule(0)
      this.dialogVisible = true
    },
    setList(list) {
      let ruleList = []
      let nexusList = []
      list.forEach(item => {
        ruleList.push({
          ruleVar: item.ruleVar,
          ruleVal: item.ruleVal,
          conditionRela: item.conditionRela
        })
        if (item.upDownRuleRela !== -1) {
          nexusList.push({
            nexus: item.upDownRuleRela
          })
        }
      })
      this.ruleForm.ruleList = ruleList
      this.ruleForm.nexusList = nexusList
    },
    addRule(index) {
      this.ruleForm.ruleList.splice(index, 0, {
        ruleVar: '',
        ruleVal: '',
        conditionRela: ''
      })
      if (this.ruleForm.ruleList.length > 1) {
        let num = index > this.ruleForm.nexusList.length ? this.ruleForm.nexusList.length : index
        this.ruleForm.nexusList.splice(num, 0, { nexus: 1 })
      }
    },
    removeRule(index) {
      this.ruleForm.ruleList.splice(index, 1)
      if (index < this.ruleForm.nexusList.length) {
        this.ruleForm.nexusList.splice(index, 1)
      } else if (index !== 0 && index === this.ruleForm.nexusList.length) {
        this.ruleForm.nexusList.splice(index - 1, 1)
      }
    },
    shiftItem(dir, index) {
      let index2 = dir === 'up' ? index - 1 : index + 1
      this.swapItem(this.ruleForm.ruleList, index, index2)
    },
    swapItem(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
    },
    submit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          let url = ''
          if (this.dialogType === 'add') {
            url = 'sys/sysUserRuleConfig/tmpl'
          } else if (this.dialogType === 'edit') {
            url = 'sys/sysUserRuleConfig'
          }
          this.$ajax({
            url: this.$ajax.setUrl(url),
            method: this.dialogType === 'add' ? 'post' : 'put',
            data: this.$ajax.setData(this.getParams())
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.dialogVisible = false
              this.$emit('refresh')
              this.$message.success(data.data || data.msg)
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    getParams() {
      let params = {
        ruleNm: this.ruleForm.ruleNm,
        ruleConfigs: []
      }
      this.ruleForm.ruleList.forEach((item, index) => {
        let rule = {
          ruleVar: item.ruleVar,
          ruleVal: item.ruleVal,
          conditionRela: item.conditionRela,
          ruleSn: index + 1
        }
        if (index > 0) {
          rule.upDownRuleRela = this.ruleForm.nexusList[index - 1].nexus
        }
        params.ruleConfigs.push(rule)
      })
      if (this.dialogType === 'edit') params.tmplId = this.ruleForm.id
      return params
    },
    clearDialog() {
      this.ruleForm.id = ''
      this.ruleForm.ruleNm = ''
      this.ruleForm.ruleList = []
      this.ruleForm.nexusList = []
    }
  }
}
</script>

<style lang="scss">
.tag-rules-edit-dialog {
  .rule-form {
    .rule-box {
      padding: 15px;
      border: 1px solid $border-color;
      text-align: center;
    }
    .rule-title {
      margin-bottom: 10px;
    }
    .button-col-left,
    .button-col-right {
      min-height: 1px;
      line-height: 40px;
      .el-button.is-circle {
        padding: 3px;
        .icon-svg {
          font-size: 16px;
        }
      }
    }
    .button-col-left {
      text-align: left;
    }
    .button-col-right {
      text-align: right;
    }
    .el-form-item {
      margin-bottom: 16px;
    }
    .nexus-col {
      margin-bottom: 16px;
    }
  }
}
</style>
